﻿using System.Collections.Generic;
using System.Linq;
using System.Xml.Linq;

namespace HMIWebDisplay
{
    public class DisplayFile
    {

        private string _pathBindings;
        private string _pathDatasource;

        private XDocument _xDocumentBindings;
        private XDocument _xDocumentDatasource;

        public IEnumerable<DisplayReference> DisplayReferenceGhosts;

        public bool HasChanges { get; set; }
        public string FileName { get; private set; }

        public DisplayFile(string pathHtmlFile)
        {
            FileName = pathHtmlFile;
            _pathBindings = pathHtmlFile.Replace(".htm", @"_files\bindings.xml");
            _pathDatasource = pathHtmlFile.Replace(".htm", @"_files\DS_datasource1.dsd");

            _xDocumentBindings = XDocument.Load(_pathBindings);
            _xDocumentDatasource = XDocument.Load(_pathDatasource);

            var displayBindings = DisplayBinding.ParseXDocument(_xDocumentBindings);
            var displayReferences = DisplayReference.ParseXDocument(_xDocumentDatasource);

            DisplayReferenceGhosts = displayReferences.Where(
                reference => displayBindings.All(
                    binding => reference.DisplayReferenceID != binding.DisplayReferenceID));
        }

        public void RemoveGhosts()
        {
            _xDocumentDatasource.Descendants().Where(
                node => DisplayReferenceGhosts.Any(
                    reference => node == reference.XElement)).Remove();
            HasChanges = true;
        }
        public void SaveChanges()
        {
            if(HasChanges)
            {
                _xDocumentDatasource.Save(_pathDatasource);
                HasChanges = false;
            }
        }
    }
}
